import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { HostileEntity } from './HostileEntity';
import { EntityType, EntityStats } from './types';
import { WorldManager } from '@/world/WorldManager';
import { ItemDropManager } from '@/world/ItemDrop';
import { BlockType } from '@/blocks/types';
import { getAudioManager } from '@/audio/AudioManager';

export class Zombie extends HostileEntity {
  private groanTimer = 0;

  constructor(id: string, position: Vec3, worldManager: WorldManager, itemDropManager?: ItemDropManager) {
    const stats: EntityStats = {
      maxHealth: 20,
      moveSpeed: 1.0,
      jumpHeight: 1.0,
      attackDamage: 3,
      attackRange: 2,
      detectionRange: 16,
      size: { width: 0.6, height: 1.8 }
    };

    super(id, EntityType.ZOMBIE, position, worldManager, stats, itemDropManager);
  }

  protected createMesh(): void {
    // 创建一个简单的僵尸模型
    const group = new THREE.Group();

    // 身体
    const bodyGeometry = new THREE.BoxGeometry(0.6, 1.2, 0.3);
    const bodyMaterial = new THREE.MeshLambertMaterial({ color: 0x4A5D23 }); // 暗绿色
    const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
    body.position.set(0, 0.6, 0);
    group.add(body);

    // 头部
    const headGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
    const headMaterial = new THREE.MeshLambertMaterial({ color: 0x6B8E23 }); // 绿色
    const head = new THREE.Mesh(headGeometry, headMaterial);
    head.position.set(0, 1.45, 0);
    group.add(head);

    // 眼睛（红色）
    const eyeGeometry = new THREE.SphereGeometry(0.05, 6, 6);
    const eyeMaterial = new THREE.MeshLambertMaterial({ color: 0xFF0000 });
    
    const leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
    leftEye.position.set(-0.1, 1.5, -0.24);
    group.add(leftEye);
    
    const rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
    rightEye.position.set(0.1, 1.5, -0.24);
    group.add(rightEye);

    // 手臂
    const armGeometry = new THREE.BoxGeometry(0.2, 0.8, 0.2);
    const armMaterial = new THREE.MeshLambertMaterial({ color: 0x4A5D23 });
    
    const leftArm = new THREE.Mesh(armGeometry, armMaterial);
    leftArm.position.set(-0.5, 0.8, 0);
    leftArm.rotation.z = Math.PI / 6; // 稍微向外伸展
    group.add(leftArm);
    
    const rightArm = new THREE.Mesh(armGeometry, armMaterial);
    rightArm.position.set(0.5, 0.8, 0);
    rightArm.rotation.z = -Math.PI / 6;
    group.add(rightArm);

    // 腿部
    const legGeometry = new THREE.BoxGeometry(0.2, 0.8, 0.2);
    const legMaterial = new THREE.MeshLambertMaterial({ color: 0x2F4F2F }); // 深绿色
    
    const leftLeg = new THREE.Mesh(legGeometry, legMaterial);
    leftLeg.position.set(-0.15, -0.4, 0);
    group.add(leftLeg);
    
    const rightLeg = new THREE.Mesh(legGeometry, legMaterial);
    rightLeg.position.set(0.15, -0.4, 0);
    group.add(rightLeg);

    // 添加一些破烂的效果
    const patchGeometry = new THREE.BoxGeometry(0.1, 0.1, 0.05);
    const patchMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 }); // 棕色补丁
    
    for (let i = 0; i < 3; i++) {
      const patch = new THREE.Mesh(patchGeometry, patchMaterial);
      patch.position.set(
        (Math.random() - 0.5) * 0.5,
        0.2 + Math.random() * 0.8,
        -0.16
      );
      group.add(patch);
    }

    // 设置阴影
    group.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.castShadow = true;
        child.receiveShadow = true;
      }
    });

    this.mesh = group;
  }

  protected onAttack(): void {
    // 僵尸攻击时的特效
    console.log(`Zombie ${this.id} groans and attacks!`);
    
    // 攻击动画（简单的前倾）
    if (this.mesh) {
      const originalRotation = this.mesh.rotation.x;
      this.mesh.rotation.x = -Math.PI / 8; // 向前倾斜
      
      // 0.2秒后恢复
      setTimeout(() => {
        if (this.mesh) {
          this.mesh.rotation.x = originalRotation;
        }
      }, 200);
    }
  }

  protected dropLoot(): void {
    // 僵尸死亡时掉落腐肉
    console.log(`Zombie ${this.id} dropped rotten flesh`);
    
    if (this.itemDropManager) {
      // 掉落腐肉 (0-2个)
      const rottenFleshCount = Math.floor(Math.random() * 3);
      if (rottenFleshCount > 0) {
        this.itemDropManager.dropItem(BlockType.ROTTEN_FLESH, rottenFleshCount, this.position);
      }
      
      // 小概率掉落铁锭
      if (Math.random() < 0.025) { // 2.5%概率
        console.log(`Zombie ${this.id} dropped rare item!`);
        this.itemDropManager.dropItem(BlockType.IRON_INGOT, 1, this.position);
      }
    }
  }

  public update(deltaTime: number): void {
    super.update(deltaTime);
    
    // 添加僵尸特有的行为
    this.addZombieBehavior(deltaTime);
  }

  private addZombieBehavior(deltaTime: number): void {
    // 定期发出呻吟声
    this.groanTimer += deltaTime;
    if (this.groanTimer >= 3 + Math.random() * 4) { // 3-7秒间隔
      this.makeGroanSound();
      this.groanTimer = 0;
    }

    // 僵尸的摇摆动画
    if (this.mesh && this.ai?.state === 'wandering') {
      this.mesh.rotation.z = Math.sin(this.age * 2) * 0.05;
      
      // 手臂摆动
      const leftArm = this.mesh.children[3];
      const rightArm = this.mesh.children[4];
      if (leftArm && rightArm) {
        leftArm.rotation.x = Math.sin(this.age * 3) * 0.3;
        rightArm.rotation.x = -Math.sin(this.age * 3) * 0.3;
      }
    }

    // 在阳光下受伤（简化版）
    // 在实际游戏中会检查光照等级
    if (Math.random() < 0.001) { // 很低的概率模拟阳光伤害
      // this.takeDamage(1);
      console.log(`Zombie ${this.id} is burning in sunlight!`);
    }
  }

  private makeGroanSound(): void {
    const groans = ['Groan...', 'Uuuugh...', 'Arrgh...', 'Braains...'];
    const randomGroan = groans[Math.floor(Math.random() * groans.length)];
    console.log(`Zombie ${this.id}: ${randomGroan}`);
    
    const audioManager = getAudioManager();
    audioManager.playSound('zombie_idle', {
      position: this.position,
      volume: 0.6
    });
  }

  // 僵尸可以破坏门（简化版）
  public canBreakDoors(): boolean {
    return true;
  }

  // 僵尸在夜晚更活跃
  public isMoreActiveAtNight(): boolean {
    return true;
  }
}